package net.minhdiep.compassview.util;
/*
 * User: Minh Diep
 * Date: 6/8/13
 * Time: 12:20 AM
 */

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import net.minhdiep.compassview.MainActivity;
import net.minhdiep.compassview.base.Item;
import org.xmlpull.v1.XmlPullParserException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.List;

public class DownloadData extends AsyncTask<String, Integer, List<Item>> {

    private Activity activity;
    private OnListener listener;

    public interface OnListener{
        public void onDownloadFinish(List<Item> result);
    }

    public DownloadData(Activity act){
        this.activity = act;
        this.listener = (OnListener) act;
    }


    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(List<Item> result) {
        super.onPostExecute(result);
        Log.d(MainActivity.DEBUG, "Listen in onPostExecute");
        listener.onDownloadFinish(result);

    }

    @Override
    protected List<Item> doInBackground(String... params) {
        // TODO Auto-generated method stub
        try {
            return downloadUrl(params[0]);
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    // Given a URL, establishes an HttpUrlConnection and retrieves
    // the web page content as a InputStream, which it returns as
    // a string.
    private List<Item> downloadUrl(String myurl) throws IOException, XmlPullParserException {
        InputStream is = null;
        Log.d(MainActivity.DEBUG, "Start downloading");
        // Only display the first 500 characters of the retrieved
        // web page content.
        try {
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /* milliseconds */);
            conn.setConnectTimeout(10000 /* milliseconds */);
            conn.setRequestMethod("GET");
            //conn.setDoInput(true);
            // Starts the query
            conn.connect();
            int response = conn.getResponseCode();
            if (response == 200) {
                is = conn.getInputStream();
                Log.d(MainActivity.DEBUG, convertStreamToString(is));
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String line;

                boolean contain = false;
                String pattern = "desc: encodeURI";


                for (int i = 0; i < 1000; i++) {
                    line = in.readLine();
                    if (line != null) {
                        if (line.contains(pattern))
                            contain = true;
                        Log.d(MainActivity.DEBUG, line);
                    }
                }

                if (contain)
                    Log.d(MainActivity.DEBUG, "contains");

                return null;
            } else
                return null;
        } catch (SocketTimeoutException e) {
            return null;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }

    public String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

}
